package com.adxon.data;

import com.adxon.MsgException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;

public class Message extends Tagging implements Refee{
	protected String	ds;			// description
	protected Kindee	sta;		// star
	protected long		sto;		// starer
	protected int		rc;			// ref count
	protected String	tx;			// text

	@Override
	public void addRef(){
		rc++;
		tm=0;
	}
	@Override
	protected void commitExt()throws MsgException{
		super.commitExt();
		commit("ds",ds);
		commit("rc",rc);
		commit("tx",tx);
	}
	@Override
	public void getAll(HttpServletRequest req){
		super.getAll(req);
		String x=StringEscapeUtils.escapeHtml4(tx);
//		req.setAttribute("Head",x==null?pk:x);
		req.setAttribute("Title",x==null?"<i>(untitled)</i>":x);
		req.setAttribute("c",StringEscapeUtils.escapeHtml4(ds==null?tx:tx+"\n\n"+ds));
		req.setAttribute("d",StringEscapeUtils.escapeHtml4(ds));
		req.setAttribute("g",StringEscapeUtils.escapeHtml4(tg));
//		req.setAttribute("k",StringEscapeUtils.escapeHtml4(pk));
		req.setAttribute("x",x);
	}
	public String getChar(){
		return tx==null?"":tx.substring(0,1);
	}
	public String getDescription(){
		return ds;
	}
	public String getStarClass(){
		if(sta==null)
			;//star();
		return sta==null?null:(sta.rt<100?(sta.rt<70?"s8s":"s8m"):null);
	}
	public long getStarer(){
		return sto;
	}
	public int getStarRate(){
		if(sta==null)
			;//star();
		return sta==null?-1:sta.rt;
	}
	@Override
	public int	getRefCount(){
		return rc;
	}
	public String getText(){
		return tx;
	}
	@Override
	public void release(){
		rc--;
		tm=0;
	}
	@Override
	public void setAll(HttpServletRequest req)throws MsgException{
		boolean f=false;
		String s=regulate(req.getParameter("c"));
		if(s!=null){
			String d,x;
			int n=s.indexOf('\n');
			if(n<0){
				d=null;
				x=s;
			}else{
				d=s.substring(n);
				x=s.substring(0,n);
			}
			if(setDescription(d))
				f=true;
			if(setText(x))
				f=true;
		}
		if(setDescription(req.getParameter("d")))
			f=true;
		if(setTags(req.getParameter("g")))
			f=true;
		if(setText(req.getParameter("x")))
			f=true;
		this.setFlag(f);
	}
	public boolean setDescription(String desc){
		String s=ds;
		ds=regulate(desc);
		return s==null?ds!=null:!s.equals(ds);
	}
	public void setStarer(Base starer){
		sto=starer.id;
	}
	public void setStarer(long starer){
		sto=starer;
	}
	public boolean setText(String text){
		String s=tx;
		tx=regulate(text);
		return s==null?tx!=null:!s.equals(tx);
	}
	/*protected void star(){
		try{
			sta=(Kindee)new Star().update(sto+"/"+id);
		}catch(MsgException e){
			sta=null;
		}
	}*/
	@Override
	public void updateExt()throws MsgException{
		super.updateExt();
		ds=updateString("ds");
		rc=updateInt("rc");
		tx=updateString("tx");
	}
}